
/**  
 * @Title: DataBaseRepositoryImpl.java  
 * @Package org.sapling.data.dao.impl  
 * @Description: TODO
 * @author DcfZero  
 * @date 2021年5月13日  
 * @version V1.0  
 */
package org.sapling.data.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.sapling.data.beans.DataOperater;
import org.sapling.data.beans.MetadataFieldTemplate;
import org.sapling.data.beans.MetadataTemplate;
import org.sapling.data.dao.DataBaseRepositoryApi;
import org.sapling.data.dao.DataCatchRepository;
import org.sapling.data.utils.SaplingTransactionManager;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;

/**
 * TODO
 * 
 * @ClassName: DataBaseRepositoryImpl
 * @author DcfZero
 * @date 2021年5月13日
 * 
 */
@Repository
public class DataBaseRepository implements DataBaseRepositoryApi {

	private static final Logger log = org.slf4j.LoggerFactory.getLogger(DataBaseRepositoryApi.class);

	@Value("${spring.datasource.platform}")
	private String platform;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private DataCatchRepository cacheRepository;

	@Autowired
	private HashMap<String, JdbcTemplate> dataSourceRepository;

	/**
	 * @param tableId
	 * @param sql
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#execute(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public int execute(String tableId, String sql) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		if(jt == null) {
			log.error("未找到{}的数据源", tableId);
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		return jt.update(sql);
	}

	/**
	 * @param operater
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#execute(org.sapling.data.beans.DataOperater)
	 */
	@Override
	public Object execute(DataOperater operater) throws Exception {
		String tableId = operater.getTableId();
		switch (operater.operate) {
		case QUERY: {
			if (operater.getPagination() > 0) {
				return findByPaging(tableId, operater.getWhereString(), null , operater.getOrderString(), operater.getPagination(), operater.getRows());
			}else {
				return operater.isTranslate() ? findBySqlAndTrans(tableId, operater.getQuerySql(tableId)) : findBySql(tableId, operater.getQuerySql(tableId));
			}
		}
		}
		return execute(tableId, operater.getQuerySql(tableId));
	}

	/**
	 * @param tableId
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#getJdbcTemplate(java.lang.String)
	 */
	@Override
	public JdbcTemplate getJdbcTemplate(String tableId) throws Exception {
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (mt == null) {
			return this.jdbcTemplate;
		}
		String connectId = this.cacheRepository.getTableConnectId(tableId);
		if (connectId == null) {
			log.error("未找到{}的元数据连接信息", connectId);
			throw new Exception(String.format("未找到%s的元数据连接信息", new Object[] { tableId }));
		}
		JdbcTemplate jt = this.dataSourceRepository.get(connectId);
		if (jt == null) {
			log.error("未找到{}的数据源", tableId);
			throw new Exception(String.format("未找到%s的数据源", new Object[] { tableId }));
		}
		return jt;
	}

	/**
	 * @param tableId
	 * @param whereString
	 * @param parameters
	 * @param orderString
	 * @param pagination
	 * @param rows
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findByPaging(java.lang.String,
	 *      java.lang.String, java.util.List, java.lang.String, int, int)
	 */
	@Override
	public List<Map<String, Object>> findByPaging(String tableId, String whereString, List<Object> parameters,
			String orderString, int pagination, int rows) throws Exception {
		if (pagination < 1) {
			pagination = 1;
		}
		if (rows < 10) {
			rows = 10;
		}
		if(parameters == null) {
			parameters = new ArrayList<Object>();
		}
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		whereString = StringUtils.isEmpty(whereString) ? " 1=1 " : whereString;
		orderString = StringUtils.isEmpty(orderString) ? null : orderString;
		String sql = this.getPagingSql(platform, mt.getTableName(), pagination, rows, parameters);
		List<Map<String, Object>> resultSet = (List<Map<String, Object>>) jt
				.queryForList(
						String.format(sql,
								new Object[] { whereString
										+ (StringUtils.isBlank(orderString) ? "" : " ORDER BY " + orderString) }),
						parameters.toArray())
				.stream().collect(Collectors.toList());
		return dictTrans(resultSet, mt.getFieldList());
	}

	/**
	 * @param tableId
	 * @param sql
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findBySql(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public List<Map<String, Object>> findBySql(String tableId, String sql) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		if(jt == null) {
			log.error("未找到{}的数据源", tableId);
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		return jt.queryForList(sql).stream().collect(Collectors.toList());
	}

	/**
	 * @param tableId
	 * @param sql
	 * @param objects
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findBySql(java.lang.String,
	 *      java.lang.String, java.lang.Object[])
	 */
	@Override
	public List<Map<String, Object>> findBySql(String tableId, String sql, Object... objects) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		if(jt == null) {
			log.error("未找到{}的数据源", tableId);
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		return jt.queryForList(sql,objects).stream().collect(Collectors.toList());
	}

	/**
	 * @param tableId
	 * @param sql
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findBySqlAndTrans(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public List<Map<String, Object>> findBySqlAndTrans(String tableId, String sql) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		return dictTrans(jt.queryForList(sql), mt.getFieldList());
	}

	/**
	 * @param tableId
	 * @param sql
	 * @param objects
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findBySqlAndTrans(java.lang.String,
	 *      java.lang.String, java.lang.Object[])
	 */
	@Override
	public List<Map<String, Object>> findBySqlAndTrans(String tableId, String sql, Object... objects) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		return dictTrans(jt.queryForList(sql,objects), mt.getFieldList());
	}

	/**
	 * @param tableId
	 * @param id
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findById(java.lang.String,
	 *      java.lang.Integer)
	 */
	@Override
	public Map<String, Object> findById(String tableId, Integer id) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("未找到{}的主键", tableId);
			throw new Exception(String.format("未找到%s的主键", tableId));
		}
		return jt.queryForMap("select * from " + tableName + " where " + pkField + " = ?", new Object[] { id });
	}

	/**
	 * @param tableId
	 * @param id
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#findByIdAndTrans(java.lang.String,
	 *      java.lang.Integer)
	 */
	@Override
	public Map<String, Object> findByIdAndTrans(String tableId, Integer id) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("未找到{}的主键", tableId);
			throw new Exception(String.format("未找到%s的主键", tableId));
		}
		Map<String, Object> result = jt.queryForMap("select * from " + tableName + " where " + pkField + " = ?", new Object[] { id });
		List<Map<String, Object>> results = new ArrayList<Map<String,Object>>(){
			{
				add(result);
			}
		};
		results = dictTrans(results, mt.getFieldList());
		return results.size() == 1 ? results.get(0) : null;
	}

	/**
	 * @param tableId
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#count(java.lang.String)
	 */
	@Override
	public long count(String tableId) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		return jt.queryForObject("SELECT COUNT(1) FROM " + tableName, Long.class).longValue();
	}

	/**
	 * @param tableId
	 * @param whereString
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#count(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public long count(String tableId, String whereString) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		if(StringUtils.isBlank(whereString)) {
			whereString = "1=1";
		}
		return jt.queryForObject("SELECT COUNT(1) FROM %s WHERE %s",new Object[]{tableName,whereString},Long.class).longValue();
	}

	/**
	 * @param tableId
	 * @param whereString
	 * @param objects
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#count(java.lang.String,
	 *      java.lang.String, java.lang.Object[])
	 */
	@Override
	public long count(String tableId, String whereString, List<Object> params) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		if(StringUtils.isBlank(whereString)) {
			whereString = "1=1";
		}
		return jt.queryForObject(String.format("SELECT COUNT(1) FROM %s WHERE %s",new Object[]{tableName,whereString},params.toArray()),Long.class).longValue();
	}

	/**
	 * @param tableId
	 * @param item
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#add(java.lang.String,
	 *      java.util.Map)
	 */
	@Override
	public int add(String tableId, Map<String, Object> item) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("在{}的注册信息中未发现主键字段", tableId);
			throw new Exception(String.format("在%s的注册信息中未发现主键字段", tableId));
		}
		parameterCheck(mt, item);
		if(!item.containsKey(mt.getPkField())) {
			item.put(pkField, getSeq(mt.getDataSourceType(), tableName, pkField, jt));
		}
		String sql = String.format("INSERT INTO " + tableName + " (%s) VALUES (%s)", new Object[] { String.join(",", item.keySet()), 
				String.join(",", Collections.nCopies(item.values().size(), "?")) });
		jt.update(sql, item.values().toArray());
		return ((Integer)item.get(pkField)).intValue();
	}

	/**
	 * @param tableId
	 * @param items
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#add(java.lang.String,
	 *      java.util.List)
	 */
	@Override
	public int add(String tableId, List<Map<String, Object>> items) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("在{}的注册信息中未发现主键字段", tableId);
			throw new Exception(String.format("在%s的注册信息中未发现主键字段", tableId));
		}
		for(Map<String,Object> item : items) {
			parameterCheck(mt, item);
			if(!item.containsKey(mt.getPkField())) {
				item.put(pkField, getSeq(mt.getDataSourceType(), tableName, pkField, jt));
			}
		}
		String sql = String.format("insert into " + tableId + " (%s) values (%s)", new Object[] { String.join(",", ((Map)items.get(0)).keySet()), 
				String.join(",", Collections.nCopies(((Map)items.get(0)).values().size(), "?")) });
		int[] rows = jdbcTemplate.batchUpdate(sql, (List)items.parallelStream()
				.map(record -> record.values().toArray()).collect(Collectors.toList()));
		return Arrays.stream(rows).sum();
	}

	/**
	 * @param tableId
	 * @param item
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#updateById(java.lang.String,
	 *      java.util.Map)
	 */
	@Override
	public int updateById(String tableId, Map<String, Object> item) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("在{}的注册信息中未发现主键字段", tableId);
			throw new Exception(String.format("在%s的注册信息中未发现主键字段", tableId));
		}
		for (MetadataFieldTemplate field : mt.getFieldList()) {
			if (!item.containsKey(field.getTableField()) || field.isKey()) {
				continue; 
			}
			Object value = item.get(field.getTableField());
			if (!field.isNull() && (value == null || StringUtils.isBlank(value + ""))) {
				throw new Exception(String.format("[%s]是一个非空字段", new Object[] { field.getTableField() }));
			}
			switch (field.getFieldType().toUpperCase()) {
				case "INT":
					item.put(field.getTableField(), StringUtils.isBlank(value + "") ? null : Integer.valueOf(Integer.parseInt(value + "")));
				case "DOUBLE":
					item.put(field.getTableField(), StringUtils.isBlank(value + "") ? null : Double.valueOf(Double.parseDouble(value + "")));
				case "DATE":
					item.put(field.getTableField(), StringUtils.isBlank(value + "") ? null : (new SimpleDateFormat("yyyy-MM-dd")).parse(value + ""));
				case "DATETIME":
					item.put(field.getTableField(), StringUtils.isBlank(value + "") ? null : (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(value + ""));
			}
		}
		Object pkValue = item.get(pkField);
		item.remove(pkField);
		List<Object> values = new ArrayList(item.values());
		values.add(pkValue);
		String sql = String.format("UPDATE " + tableId + " SET %s WHERE " + pkField + " = ?", new Object[] { String.join(" = ? , ", item.keySet()).concat(" = ?") });
		return jdbcTemplate.update(sql, values.toArray());
	}

	/**
	 * @param tableId
	 * @param id
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#deleteById(java.lang.String,
	 *      java.lang.Integer)
	 */
	@Override
	public int deleteById(String tableId, Integer id) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		MetadataTemplate mt = this.cacheRepository.getMetadataTemplate(tableId);
		if (!checkTableMetaDataInfo(tableId, jt, mt)) {
			throw new Exception(String.format("未找到%s的数据源", tableId));
		}
		String tableName = mt.getTableName();
		String pkField = mt.getPkField();
		if(StringUtils.isBlank(pkField)) {
			log.error("在{}的注册信息中未发现主键字段", tableId);
			throw new Exception(String.format("在%s的注册信息中未发现主键字段", tableId));
		}
		return jt.update("DELETE FROM " + tableId + " WHERE " + pkField + " = ?", new Object[] { id });
	}

	public boolean checkTableMetaDataInfo(String tableId, JdbcTemplate jt, MetadataTemplate mt) {
		if (jt == null) {
			log.error("未找到{}的数据源", tableId);
			return false;
		}
		if (mt == null) {
			log.error("未找到{}的元数据连接信息", tableId);
			return false;
		}
		return true;
	}

	/**
	 * @param dbType
	 * @param tableName
	 * @param pagination
	 * @param rows
	 * @param params
	 * @return
	 * @see org.sapling.data.dao.DataBaseRepository#getPagingSql(java.lang.String,
	 *      java.lang.String, int, int, java.util.List)
	 */
	@Override
	public String getPagingSql(String dbType, String tableName, int pagination, int rows, List<Object> params) {
		switch (dbType) {
		case "mysql":
		case "mariadb":
		case "postgresql":
			params.add(Integer.valueOf(rows));
			params.add(Integer.valueOf((pagination - 1) * rows));
			return "SELECT * FROM " + tableName + " WHERE %s LIMIT ? OFFSET ?";
		}
		params.add(0, Integer.valueOf(pagination * rows));
		params.add(1, Integer.valueOf((pagination - 1) * rows));
		return "SELECT * FROM (SELECT ROWNUM RN,t.* FROM " + tableName + " t WHERE ROWNUM <= ?) WHERE RN > ? AND %s";
	}

	/**
	 * @param result
	 * @param dictFields
	 * @return
	 * @throws Exception
	 * @see org.sapling.data.dao.DataBaseRepository#dictTrans(java.util.List,
	 *      java.util.List)
	 */
	@Override
	public List<Map<String, Object>> dictTrans(List<Map<String, Object>> resultSet, List<MetadataFieldTemplate> fields)
			throws Exception {
		Map<String, Map<String, String>> dictFieldMap = new HashMap<String, Map<String, String>>();
		long start = System.currentTimeMillis();
		for (MetadataFieldTemplate field : fields) {
			if (!StringUtils.isBlank(field.getFieldDict()) && field.getFieldDict().toLowerCase() != "null") {
				Map<String, String> dictMap = cacheRepository.getDict(field.getFieldDict());
				if (dictMap == null) {
					log.error("未能找到{}的字典数据源", field.getFieldDict());
				} else {
					dictFieldMap.put(field.getTableField(), dictMap);
				}
			}
		}
		Map<String, Object> dictSet = new HashMap<String, Object>();
		if (dictFieldMap.size() > 0) {
			for (Map<String, Object> set : resultSet) {
				for (String transField : set.keySet()) {
					if (dictFieldMap.containsKey(transField)) {
						String value = String.valueOf(set.get(transField)) == "null" ? ""
								: String.valueOf(set.get(transField));
						String transValue = dictFieldMap.get(transField).get(value);
						dictSet.put(transField + "_desc", transValue);
					}
				}
				set.putAll(dictSet);
				dictSet.clear();
			}
		}
		log.info("字典翻译{{}}条数据,耗时{{}}毫秒",resultSet.size(),Long.valueOf(System.currentTimeMillis() - start));
		return resultSet;
	}

	/** 
	 * @param param
	 * @throws Exception 
	 * @see org.sapling.data.dao.DataBaseRepositoryApi#parameterCheck(java.util.Map) 
	 */
	private void parameterCheck(MetadataTemplate mt,Map<String, Object> param) throws Exception {
		//param.entrySet().stream().collect(Collectors.toMap(k -> ((String)k.getKey()).toLowerCase(), v -> v.getValue()));
		for(MetadataFieldTemplate mft : mt.getFieldList()) {
			String fieldName = mft.getTableField();
			Object value = param.get(fieldName);
			if(!param.containsKey(fieldName)) {
				continue;
			}
			if(!mft.isNull() && !mft.isKey() && (value == null || StringUtils.isBlank(value + ""))) {
				throw new Exception(String.format("[%s]是一个非空字段", mft.getTableField()));
			}
			String type = mft.getFieldType().toUpperCase(); 
			switch (type) {
			case "VARCHAR":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : value + "");
				break;
			case "TEXT":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : value + "");
				break;
			case "INT":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : Integer.valueOf(Integer.parseInt(value + "")));
				break;
			case "DOUBLE":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : Double.valueOf(Double.parseDouble(value + "")));
				break;
			case "DATE":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : (new SimpleDateFormat("yyyy-MM-dd")).parse(value + ""));
				break;
			case "DATETIME":
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(value + ""));
				break;
			default : 
				log.info("{}数据类型注册信息无法解析",fieldName);
				param.put(fieldName, StringUtils.isBlank(value + "") ? null : value + "");
				break;
			}
		}
	}

	/** 
	 * @param dbType
	 * @param tableName
	 * @param pkField
	 * @param jt
	 * @return
	 * @throws Exception  
	 * dbType means {@link org.sapling.data.utils.DataTableFieldTypeTranslateUtils#translateFieldType}
	 */
	private int getSeq(int dbType, String tableName, String pkField, JdbcTemplate jt) throws Exception {
		switch (dbType) {
		case 1:
			return ((Integer)jt.queryForObject("SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '"+ tableName +"'", Integer.class).intValue());
		case 2:
			return ((Integer)jt.queryForObject("SELECT " + tableName + "_" + pkField + "_seq.nextval FROM dual", Integer.class)).intValue();
		case 3:
			return ((Integer)jt.queryForObject("SELECT nextval('" + tableName + "_" + pkField + "_seq')", Integer.class)).intValue();
		}
		return 0;
	}

	/** 
	 * @param tableId
	 * @return
	 * @throws Exception 
	 * @see org.sapling.data.dao.DataBaseRepositoryApi#beginTransaction(java.lang.String) 
	 */
	@Override
	public SaplingTransactionManager beginTransaction(String tableId) throws Exception {
		JdbcTemplate jt = this.dataSourceRepository.get(this.cacheRepository.getTableConnectId(tableId));
		if(jt == null) {
			throw new Exception(String.format("未能找到%s的数据源", tableId));
		}
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(jt.getDataSource());
		return new SaplingTransactionManager(transactionManager);
	}


}
